import { isFunction } from "../utils/check"
import { useWebEnv, useWebEvn, useUrlParams } from "../utils"

export default class Base {
  constructor(config = {}) {
    this.isReady = false
    this.core = null
    this.env = config.env
    this.config = config
    this.events = new Map()
    this.webEnv = useWebEnv()
    this.webEvn = useWebEvn()
    this.urlParams = useUrlParams()
    this.systemInfo = uni.getSystemInfoSync()
  }

  ready(handler = () => {}) {
    if (this.isReady) {
      handler(this)
    } else {
      const handlers = this.events.get("ready")
      if (handlers) {
        handlers.push(handler)
      } else {
        this.events.set("ready", [handler])
      }
    }
  }

  error(handler = () => {}) {
    const handlers = this.events.get("error")
    if (handlers) {
      handlers.push(handler)
    } else {
      this.events.set("error", [handler])
    }
  }

  emit(name, ...args) {
    let handlers = this.events.get(name)
    if (handlers) {
      handlers.slice().map((handler) => {
        if (typeof handler === "function") handler(...args)
      })
    }
  }

  checkApi(api = "") {
    return this.apiList.includes(api)
  }

  checkInit(params = {}) {
    return new Promise((resolve, reject) => {
      if (this.isReady) {
        resolve(this)
        this.successCallback(params)
      } else {
        // 再次初始化一次
        this.init()
          .then(() => {
            this.isReady = true
            resolve(this)
            this.successCallback(params, this)
          })
          .catch((err) => {
            reject(err)
            this.failCallback(params, err)
          })
      }
    })
  }

  checkLogin(params = {}) {
    return new Promise((resolve, reject) => {
      this.checkInit({
        success: () => {
          if (this.isLogin) {
            resolve()
            this.successCallback(params)
          } else {
            this.login()
              .then((res) => {
                this.isLogin = true
                resolve(res)
                this.successCallback(params, res)
              })
              .catch((err) => {
                reject(err)
                this.failCallback(params, err)
              })
          }
        },
        fail: (err) => {
          reject(err)
          this.failCallback(params, err)
        }
      })
    })
  }

  successCallback(params, data) {
    isFunction(params.success) && params.success(data)
    isFunction(params.complete) && params.complete()
  }

  failCallback(params, err) {
    isFunction(params.fail) && params.fail(err)
    isFunction(params.complete) && params.complete()
  }

  log(str) {
    // const evn = useWebEvn()
    console.log(str)
  }
}
